package com.ncmmall.mall.controller.business.withdraw;

import cn.hutool.core.date.DateUtil;
import com.ncmmall.application.business.withdraw.MerchantWithdrawApplication;
import com.ncmmall.domain.business.setting.SystemSetting;
import com.ncmmall.domain.business.trading.MerchantWithdrawApply;
import com.ncmmall.domain.business.trading.TradingLog;
import com.ncmmall.domain.security.user.QWebUser;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 交易流水
 *
 * @author likaikai
 * @date 2019-07-22 15:38:57
 */
@Controller
@RequestMapping("/supplier/trading")
@Slf4j
public class MerchantTradingController {

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private MerchantWithdrawApplication merchantWithdrawApplication;

    /**
     * 交易流水列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model, PageParams pageParams, TradingLog params) {

        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo()).setPageSize(20);

        Map<String, Object> map = new HashMap<>();
        map.put("id", Securitys.currentUser().getId());

        String sql = buildSql("select t from TradingLog t where t.merchant.id = :id ", map, params);
        QueryPage<TradingLog> page = queryChannelService.findPage(sql, pageRequest.setParams(map), TradingLog.class);

        double totalAmount = queryChannelService.selectSum("select ifnull(sum(o.amount),0) from mall_trading_log o where o.merchant_id = :id and type in (1,4,5) ", ImmutableMap.of("id", Securitys.currentUser().getId()));
        double noAmount = queryChannelService.findOne(QWebUser.webUser.eq(Securitys.currentUser()), WebUser.class).getBalance();
        double applyAmount = queryChannelService.selectSum("select ifnull(sum(o.amount),0) from mall_merchant_withdraw_apply o where o.status in(1,2,4) and o.merchant_id = :id ", ImmutableMap.of("id", Securitys.currentUser().getId()));
        double amount = queryChannelService.selectSum("select ifnull(sum(o.amount),0) from mall_merchant_withdraw_apply o where o.status = 5 and o.merchant_id = :id ", ImmutableMap.of("id", Securitys.currentUser().getId()));

        model.addAttribute("params", params);
        model.addAttribute("page", page);
        model.addAttribute("totalAmount", totalAmount);
        model.addAttribute("noAmount", noAmount);
        model.addAttribute("applyAmount", applyAmount);
        model.addAttribute("amount", amount);

        return "supplier/trading/list";
    }


    /**
     * 申请提现
     */
    @RequestMapping(value = "/applyWithdraw", method = RequestMethod.GET)
    private String applyWithdraw(Model model) {

        SystemSetting setting = queryChannelService.queryOneEntity("select * from mall_system_setting limit 1", Collections.emptyMap(), SystemSetting.class);

        model.addAttribute("_method", "PUT")
                .addAttribute("withdraw", new MerchantWithdrawApply())
                .addAttribute("setting", setting)
                .addAttribute("merchant", queryChannelService.findOne(QWebUser.webUser.id.eq(Securitys.currentUser().getId()), WebUser.class));

        return "supplier/trading/applyWithdraw";
    }

    /**
     * 申请提现
     */
    @RequestMapping(value = "/applyWithdraw", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> applyWithdraw(MerchantWithdrawApply withdrawApply) {
        try {
            withdrawApply.setMerchant(Securitys.currentUser());
            merchantWithdrawApplication.applyWithdraw(withdrawApply);
            return ImmutableMap.of("status", true);
        } catch (Exception e) {
            log.error("[编辑商品基本信息异常]", e);
            return ImmutableMap.of("status", false);
        }
    }


    /**
     * 条件查询
     */
    private String buildSql(String sql, Map<String, Object> map, TradingLog params) {

        if (!Strings.isNullOrEmpty(params.getOrderNo())) {
            sql += " and t.orderNo = :no ";
            map.put("no", params.getOrderNo());
        }

        if (!Strings.isNullOrEmpty(params.getBeginTime())) {
            sql += " and t.createTime >= :btime ";
            map.put("btime", DateUtil.parse(params.getBeginTime(), "yyyy-MM-dd").toJdkDate());
        }

        if (!Strings.isNullOrEmpty(params.getEndTime())) {
            sql += " and t.createTime <= :etime ";
            map.put("etime", DateUtil.parse(params.getBeginTime(), "yyyy-MM-dd").toJdkDate());
        }

        return sql + " order by t.createTime desc";
    }


}
